﻿using System;
using System.Collections;
using System.Web.Mvc;
using Huirui.Cavan.Application.MainBoundedContext.SalesModule;
using Huirui.Cavan.Domain.MainBoundedContext.SalesModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Presentation.Seedwork;
using Huirui.Cavan.Presentation.ViewModel.SalesModule;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.Seedwork;
using Newtonsoft.Json;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using System.Collections.Generic;

namespace Huirui.Cavan.Presentation.Controller.SalesModule
{
    #region SalesPrice

    public class SalesPriceController : EntityController<SalesPrice, string, SalesPriceSearch, ISalesPriceViewModel, ISalesPriceAppService>, ISalesPriceController
    {
        public override string ControllerName
        {
            get { return ControllerConst.SALESPRICE; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }

        public SalesPriceController()
        {
            this.Model = ModelFactory.CreateModel<ISalesPriceViewModel>();
        }

        [ActionName(ActionConst.ADD)]
        [HttpGet]
        [ActionPermissionAttribute(Name = "salesprice_query")]
        public ActionResult AddSalesPrice(string id)
        {
            if (id.IsNotEmpty())
            {
                this.Model.Item = this.AppService.GetById(id);
            }
            else
            {
                this.Model.Item = new SalesPrice();
                this.Model.Item.ModifyDate = DateTime.Now;
                this.Model.Item.StartDate = DateTime.Now;
                this.Model.Item.Id = "";
            }

            return View("~/Views/Sales/v1/addSalesPrice.cshtml", this.Model);
        }

        [ActionName(ActionConst.ADD)]
        [HttpPost]
        [ActionPermissionAttribute(Name = "salesprice_edit")]
        public JsonResult AddSalesPrice(SalesPriceViewModel model)
        {
            BoolResult jsonResult = null;
            BoolGenericResult<SalesPrice> result = null;
            model.Item.Type = (SalesIdentifier.PriceType)model.Type;
            model.Item.Customers = JsonConvert.DeserializeObject<IList<Customer>>(model.Customers);
            model.Item.SalesPriceDetails = JsonConvert.DeserializeObject<IList<SalesPriceDetail>>(model.SalesPriceDetails);

            result = this.AppService.AddOrUpdate(model.Item);

            jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult, "application/json");
        }
    }
    #endregion
}